//TODO: License Header.

/*
This code is licensed under the BSD license.

*/
package analysis.metrics

import primitives.cluster.ClusterHead
import primitives.graph.Node
import search.util.TreeLoader2
import static Math.min
import primitives.cluster.*;
import primitives.graph.*;
import search.fitnessfunctions.BunchTurboMQFitnessFunction;


class BottomMQMetric extends Metric{

	double evaluate(ClusterHead tree){
		
		



		//depth--;

		int depth = search.fitnessfunctions.LevelLimitedMQ.maxDepth(tree)-1; //need to sub 1 because level will be 1 more than the max value when in the inner loop below.
		
		ClusterHead extended = search.fitnessfunctions.LevelLimitedMQ.extendLayers(tree, 0)

//		System.err.println("depth is $depth")



		
	


		List<IClusterLevel> current = new ArrayList<IClusterLevel>();
		current.add(tree);
		HashSet<IClusterLevel>  current_store;


		while(!current.isEmpty()){



			List<IClusterLevel> next = new ArrayList<IClusterLevel>();

			/* Number of IClusterLevels in next with more than one child.
				If count is greater than 0 then that means this level is OK as the bottom level.
				If count ever hits 0 current_store doesn't update, so it contains the last
				level where at least one of the nodes had more than one children.
			 */
			int count = 0;
//			System.err.println("iter $current.size");
			HashSet<IClusterLevel> children = new HashSet<IClusterLevel>();
			
			
			for(IClusterLevel c: current){

//				current_store.add(c);


				children.addAll(((ClusterNode)c).getChildren() );			
				 
			}

			for(IClusterLevel d: children){
					if(d.getNodes().size() > 1 ){
						count++;
						
					//	System.err.println("inc");
					}	
					if(d.encapsulates()) next.add(d);

					
			}
			
			if(count != 0){
				current_store = new HashSet<IClusterLevel> ();
				current_store.addAll(children)
//				System.err.println("Using $depth for evaluation due to $count.")
			}
			
			depth--;
			current = next;
		}




	
		BunchTurboMQFitnessFunction ff = new BunchTurboMQFitnessFunction();
		
		ClusterHead temp = new ClusterHead(current_store, true);
		
		ff.setTree(temp );
		return ff.evaluate(temp);
        
	}
	
	public static void getBottom(ClusterHead ch){
		 
	}

	public static void main(String[] args){
		new BottomMQMetric().proc(args);
	}

	
}